<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身会员购课</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/badge.css') }}">

</head>
<body>
    {% include 'show_ins_info.html' %}
    <div id="inputContents">
        <h3>会员编码及姓名：</h3>
        
        <input type="text" id="cusNameInput" style="width: 120px;" oninput="handleInput()">
        <ul id="cusNameResultList"></ul>
        <div id='stageBlock' style="text-align: center;width:100px;background-color: aliceblue;border: 1px snow solid; border-radius: 12px;margin-top:8px;padding:10px;">
                <div id="stage"></div>    
                <div id="offsetAmount"></div>            
                <div id="badge"></div>
        </div>
        <p></p>

        <button id='showHisBut' onclick="get_cus_buy()">查看购课记录</button>
        <div id="noBuyHisPrompt"></div>
        <div id="buyHistory" class="buy-list"></div>

        <h3>购课日期</h3>
        <div id="date">
            <form>
                <label for="dateInput"></label>
                <input type="date" id="dateInput" name="dateInput">
                <br>
            </form>
        </div>

        <div id="vcBox" style="display: none;">
            <h3 style="color:rgb(191, 54, 54)">会员有可用的卡券</h3>
            <select id="vcSel"><option value="0">不使用卡券</option></select>
        </div>


        <h3>会员购课卡号</h3>
        <!-- <input type="text" id="buyCode" style="width: 190px;" oninput="isValidDate()" onclick="get_cus_buy()" > -->
        <select id="buyCodeSelect"></select>
        
        <div id="buyCodeErr" class="inline2"></div>
        <p></p>    

        <ul id="resultList"></ul>
        <ul id="cus_info"></ul>

        <h3>购课类型</h3>
        <select id="buyType"  onchange="generateBuyCodeSelect();generateClsNameSelect();">
            <!-- <option value="">请选择</option> -->
        </select>
        <div id="errBuyType" class="inline2"></div>
        
        <h3>购课名称</h3>
        <select id="buyClsName" onchange="generateBuyCodeSelect();">
            <!-- <option value="">请选择</option> -->
        </select>

        <h3>购课节数</h3>
        <input type="number" id="buyNum" name="buyNum" step="1" min="0" oninput="onInputBuyNumDaysCheck(this.id)">
        <div id="errBuyNum" class="inline2" ></div>
        <p></p>

        <h3>购课时长（天）</h3>
        <input type="number" id="buyDays" name="buyDays" step="1" min="0" oninput="onInputBuyNumDaysCheck(this.id)">
        <div id="errBuyDays" class="inline2" ></div>
        <p></p>

        <h3>可约课时段</h3>
        <div>
            <select id="validTime">
                <option value="all_day">正常营业时间</option>
                <option value="0900-1000">09:00-10:00</option>
                <option value="1000-1100">10:00-11:00</option>
                <option value="1400-1500">14:00-15:00</option>
                <option value="1500-1600">15:00-16:00</option>
            </select>
        </div>       
        <p></p>

        <h3>应收金额</h3>
        <input type="number" id="pay" name="pay" step="0.01" min="0">
        <p></p>

        <h3>实收金额</h3>
        <input type="number" id="realPay" name="realPay" step="0.01" min="0" oninput="calRealPay();">
        <div id="realPayWithVc"></div>
        <label><input type="checkbox" id="consWithPay" name="consWithPay" value="yes" checked> 与应收一致</label>
        <p></p>

        <h3>收款人</h3>
        <select id="cashier">
            <option value="">请选择</option>
        </select>

        <h3>收入类别</h3>
        <select id="incomeType">
            <option value="">请选择</option>
        </select>

        <h3>备注</h3>
        <input type="text" id="comment" style="width: 190px;height: 80px;">
        
        <h3>管理员备注</h3>
        <input type="text" id="admCmt" name="admCmt" style="width: 190px;height: 80px;">

        
        <div  class="inline2" id="other_info" >
            <p></p>
            <p></p>
            <div  id="open_cus_fn_res"></div>
            <p></p>
            <div id="err_no_result"></div>
        </div>

        <div class="inline2" id="status"></div>
    </div>
    <p></p>
    <div id="showDealResult" style="display:none">正在购课，请稍等。</div>
    <div><button id='submitBtn' style="margin-right:5px;" onclick="submit()">提交</button></div>

    <script src="../static/js/moment.min.js"></script>
    <script src="../static/js/common.js"></script>
    <script> 
        let insId;
        let cus_list;
        let selectedName;
        let tmplt_info;
        let buy_list;
        let insRole;
        let insName;
        let buyFlowId='';
        let startDate;
        let endDate;
        let allError={'dateError':0,'buyNumError':0};
        let vcData;
        let cusTotalAmount=0;
        

        // 使用DOMContentLoaded事件监听，在页面加载完成后触发获取数据的操作
        document.addEventListener("DOMContentLoaded", function() {   
            // loginCheck();
            // const buyCodeBox=document.getElementById('buyCode');
            const historyDiv=document.getElementById('buyHistory');

            //面加载时，在页面上绑定点击时隐藏购课编码div的动作
            document.addEventListener("click",function(){
                historyDiv.style.display='none';
            });

            const showBuyHisButton=document.getElementById('showHisBut');
            
            showBuyHisButton.addEventListener('click', function (event) {
            // 阻止事件冒泡，使得点击 input 不会触发 document 的点击事件
                event.stopPropagation();
            // 显示 history 框
                historyDiv.style.display = 'block';
            });


            selectToday(id='dateInput',format='date');

            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                tmplt_info=data;
                console.log(data)
                generateBuyTypeSelect(data);
                generateClsNameSelect(data);
                showBuyTypePrompt();
                cashierSelect(data);
                incomeTypeSelect(data);
                  })
                .catch(error => console.error('Error:', error));


            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                //将data赋值给块变量cus_list，供后面的handleInput使用
                    cus_list=data
                })
            .catch(error => console.error('Error:', error));
            // 这里可以通过 JavaScript 来遍历某个文件夹中的文件，生成名字列表
            // var names = ["Alice", "Bob", "Charlie", "David"];    
            
            const insInfos=hideInsSelectBlockAndGetInsInfo();
            insId=insInfos['sessionInsId'];
            insName=insInfos['sessionInsName'];
            insRole=insInfos['sessionInsRole'];

            //教练角色不允许进入该页面，返回Index
            if(insRole==='ins'){
                window.location.replace('./index');
            }

            generateBuyCodeSelect();
            // console.log(insInfos)

            getCusStageConfig();

            //隐藏会员等级显示div
            document.getElementById('stageBlock').style.display='none';
            
            
        });


        function getCusStageConfig(){
            fetch('/get_cus_stage_config', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {                
                cusStageConfig=data.stage_config;
                console.log('cusStageConfig list:',cusStageConfig);
                  })
                .catch(error => console.error('Error:', error)); 

        }
        
        function hide_cus_buy(){
            document.getElementById('buyHistory').style.display='none';
            document.getElementById('noBuyHisPrompt').innerText='';
        }

        function get_cus_buy(){
            document.getElementById('buyHistory').style.display='block';
            const buyDays=document.getElementById('buyDays');
            const buyNum=document.getElementById('buyNum');
            const buyType=document.getElementById('buyType');
            const buyPay=document.getElementById('pay');   
            const errBuyType=document.getElementById('errBuyType');
            const realPay=document.getElementById('realPay');
            const incomeType=document.getElementById('incomeType');
            const buyClsName=document.getElementById('buyClsName');
            
            buyDays.disabled=false;
            buyNum.disabled=false;
            buyType.disabled=false;
            buyPay.disabled=false;
            incomeType.disabled=false;

            realPay.value='';
            buyPay.value='';
            buyNum.value='';


            fetch('/get_cus_buy',{
            method:"POST",
            headers:{
                "Content-Type":"application/json"
            },
            body: JSON.stringify({'cusIdName':document.getElementById('cusNameInput').value.trim()})
            })
            .then(response=>response.json())
            .then(jsonDataRes=>{
                // console.log('get cus buy history:',jsonDataRes)
                const tableContainer = document.getElementById('buyHistory');
                const noBuyHisPrompt=document.getElementById('noBuyHisPrompt');
              
                tableContainer.innerHTML='';
                noBuyHisPrompt.innerHTML='';
                const jsonData=jsonDataRes['buy_stat_list']
                if(jsonData){
                    // 创建表格元素
                    const table = document.createElement('table');

                    // 创建表头行
                    const headerRow = table.insertRow();
                    headerRow.classList.add('header-row');
                    for (const header of ['购课编码','课程类型','应收金额','实收金额','未收金额','收款次数','收款日期']) {
                    const cell = headerRow.insertCell();
                    cell.textContent = header;
                    }

                    // 创建表格内容
                    for (let i = 0; i < Object.keys(jsonData).length; i++) {
                    const row = table.insertRow();
                    for (let j=0;j<jsonData[0].length-2;j++) {
                        const cell = row.insertCell();

                        cell.innerHTML = `${jsonData[i][j]}`;    
                        //当未收金额大于0时，标红
                        if(j===4 && jsonData[i][4]>0){   
                            //额度大于1，为代金券
                            if(parseFloat(jsonData[i][8])>1)       {
                                if(parseFloat(jsonData[i][4])===parseFloat(jsonData[i][8])){
                                cell.innerHTML = `<span style='color:red;'>0*</span>`;    
                                }  
                                if(parseFloat(jsonData[i][4])>parseFloat(jsonData[i][8])){
                                    cell.innerHTML = `<span style='color:red;'>${parseFloat(jsonData[i][4])-parseFloat(jsonData[i][8])}*</span>`;    
                                }    
                            //额度小于1，为折扣券      
                            }else{                    
                                if(parseFloat(jsonData[i][4])>parseFloat(jsonData[i][3])*(1-parseFloat(jsonData[i][8]))){
                                    cell.innerHTML = `<span style='color:red;'>${parseFloat(jsonData[i][4])-parseFloat(jsonData[i][3])*(1-parseFloat(jsonData[i][8]))}*</span>`;    
                                }   
                            }
                                      
                            
                        }   
                    }
                    
                        
                        // row.addEventListener('click', function(){
                        //     // 在点击时获取购课编码并打印
                        //     const buyCode = jsonData[i][0]; // 假设购课编码在第一列
                        //     console.log('购课编码:', buyCode);
                        // // 在这里可以执行其他操作，如传递购课编码给其他函数等等
                        // });

                        //点击选择时执行以下操作：禁用一些项目的录入
                        (function(index) {
                            row.addEventListener('click', function(event) {
                            // 阻止事件冒泡，使得点击 history 不会触发 document 的点击事件
                                event.stopPropagation();
                                const buyCodeErrBox=document.getElementById('buyCodeErr');
                                incomeType.disabled=false;
                                buyCodeErrBox.innerText='';
                                realPay.value='';
                                buyNum.value='';
                                buyDays.value='';
                                buyPay.value='';


                                if(document.getElementById('buyType').value==='常规课程'){
                                    // document.getElementById('buyDays').disabled=true;
                                    if(buyClsName.value==='私教'){
                                        buyNum.value='';
                                        buyDays.value='';              
                                        buyDays.setAttribute('disabled','true');
                                        buyNum.disabled=false;
                                    }else if(buyClsName.value==='9.9元私教'){
                                        buyNum.value='1';
                                        buyDays.value='30';              
                                        buyDays.setAttribute('disabled','true');
                                        buyNum.setAttribute('disabled','true');
                                        document.getElementById('pay').value="9.9";
                                        document.getElementById('real_pay').value="9.9";                            
                                    }else if(buyClsName.value==='活动赠课'){
                                        // buyNum.value='1';
                                        // buyDays.value='30';              
                                        buyDays.setAttribute('disabled','true');
                                        // buyNum.setAttribute('disabled','true');
                                        document.getElementById('pay').value="0";
                                        document.getElementById('real_pay').value="0";
                                    }else{
                                        buyNum.value='';
                                        buyDays.value='';              
                                        buyDays.setAttribute('disabled','true');
                                        buyNum.disabled=false;
                                    }                
                                }else if(document.getElementById('buyType').value ==='限时课程'){
                                    document.getElementById('buyDays').disabled=false;}
                                
                            //隐藏buyhistory框
                                const historyDiv=document.getElementById('buyHistory');
                                historyDiv.style.display='none';

                                const buyCode = jsonData[index][0]; // 课编码在第一列
                                const notPayAmount=jsonData[index][4]; //未收金额
                                // console.log('购课编码:', buyCode);
                                // document.getElementById('buyCodeSelect').value=buyCode;

                                //改写卡号的选择及相关设置
                                document.getElementById('buyCodeSelect').innerHTML='';
                                const cardIdOpt=document.createElement('option');
                                cardIdOpt.value=buyCode;
                                cardIdOpt.text=buyCode.split('-')[0];
                                document.getElementById('buyCodeSelect').appendChild(cardIdOpt);
                                
                                // if()
                                
                                const buyRecords=Object.keys(buy_list).map(key => (buy_list[key]));
                                // console.log(buyRecords);
                                buyRecords.forEach(buyRec=> {
                                    if(buyRec['购课流水号']===buyCode){
                                        document.getElementById('buyType').value=buyRec['购课类型'];
                                        document.getElementById('buyNum').value=buyRec['购课节数'];
                                        document.getElementById('buyClsName').value=buyRec['课程名称'];
                                        document.getElementById('buyDays').value=buyRec['购课时长（天）'];
                                        document.getElementById('pay').value=buyRec['应收金额'];
                                        document.getElementById('incomeType').value=buyRec['收入类别'];
                                        if(parseFloat(notPayAmount)>0){
                                            realPay.value=notPayAmount;
                                        }

                                    }
                                });

                                buyDays.disabled=true;
                                buyNum.disabled=true;
                                buyType.disabled=true;
                                buyPay.disabled=true;
                                incomeType.disabled=true;
                                buyClsName.disabled=true;
                                errBuyType.innerText=''


                                // if(document.getElementById('buyType').value==='常规课程'||document.getElementById('buyType').value==='常规团课'){
                                //     document.getElementById('buyDays').disabled=true;
                                //     document.getElementById('buyType').disabled=true;
                                //     document.getElementById('buyNum').disabled=true;
                                // }else if(document.getElementById('buyType').value ==='限时课程' ||document.getElementById('buyType').value ==='限时团课'){
                                //     document.getElementById('buyDays').disabled=false;
                                //     document.getElementById('buyType').disabled=false;
                                //     document.getElementById('buyNum').disabled=false;
                                // }
                            });
                        })(i);


                        // 将表格添加到div中
                        tableContainer.appendChild(table);
                        
                    }                   
                }else{
                    // 如没有购课历史，则根据购课类型禁用或打开购课时长
                    // if(document.getElementById('buyType').value==='常规课程'){
                    //                 document.getElementById('buyDays').disabled=true;
                    //             }else if(document.getElementById('buyType').value ==='限时课程'){
                    //                 document.getElementById('buyDays').disabled=false;}

                    if(buyTypeSelect.value==='常规课程'){      
                        if(buyClsName.value==='私教'){
                            buyNum.value='';
                            buyDays.value='';              
                            buyDays.setAttribute('disabled','true');
                            buyNum.disabled=false;
                        }else if(buyClsName.value==='9.9元私教'){
                            buyNum.value='1';
                            buyDays.value='30';              
                            buyDays.setAttribute('disabled','true');
                            buyNum.setAttribute('disabled','true');
                        }else if(buyClsName.value==='活动赠课'){
                            buyNum.value='';
                            buyDays.value='';              
                            buyDays.setAttribute('disabled','false');
                            buyNum.setAttribute('disabled','false');
                        }else{
                            buyNum.value='';
                            buyDays.value='';              
                            buyDays.setAttribute('disabled','true');
                            buyNum.disabled=false;
                        }                
                    }
                    noBuyHisPrompt.innerText='未查询到购课记录';

       
                }
                
            })
            .catch(error=>{
                console.log(error)
            });
        }

        function onInputBuyNumDaysCheck(id){
            console.log(id)
            // console.log(document.getElementById('buyType').value,document.getElementById('buyNum').value,document.getElementById('buyDays').value)
            const InputBox=document.getElementById(id)
            document.getElementById('errBuyDays').innerText='';
            document.getElementById('errBuyNum').innerText='';
            document.getElementById('errBuyType').innerText='';
         
            if(document.getElementById('buyType').value==='限时课程'){
                if(document.getElementById('buyDays').value==='' &&  document.getElementById('buyNum').value ||
                    document.getElementById('buyDays').value===0 &&  document.getElementById('buyNum').value){
                    document.getElementById('errBuyDays').innerText='限时课程必须输入天数';
                }else if(document.getElementById('buyDays').value &&  document.getElementById('buyNum').value==='' ||
                    document.getElementById('buyDays').value &&  document.getElementById('buyNum').value===0){
                    document.getElementById('errBuyNum').innerText='限时课程必须输入节数';
                }else if(!(document.getElementById('buyDays').value &&  document.getElementById('buyNum').value)){
                    document.getElementById('errBuyType').innerText='限时课程必须同时输入节数和天数';
                }else{
                    document.getElementById('errBuyDays').innerText='';
                    document.getElementById('errBuyNum').innerText='';
                    document.getElementById('errBuyType').innerText='';
                }
                
            }

        }

        function showBuyTypePrompt(){
            const buyTypeSelect=document.getElementById('buyType');
            // console.log(buyTypeSelect.value);
            const buyDaysInput=document.getElementById('buyDays');       
            const buyClsName=document.getElementById('buyClsName');    
            const buyNum=document.getElementById('buyNum');
            buyNum.value='';
            buyDaysInput.value='';

            buyDaysInput.removeAttribute('disabled');
            buyNum.removeAttribute('disabled');
            document.getElementById('errBuyDays').innerText='';
            document.getElementById('errBuyNum').innerText='';
            document.getElementById('errBuyType').innerText='';
            if(buyTypeSelect.value==='限时课程'){                    
                buyDaysInput.removeAttribute('disabled');
                if(document.getElementById('buyDays').value==='' &&  document.getElementById('buyNum').value ||
                    document.getElementById('buyDays').value===0 &&  document.getElementById('buyNum').value){
                    document.getElementById('errBuyDays').innerText='限时课程必须输入天数'
                }else if(document.getElementById('buyDays').value &&  document.getElementById('buyNum').value==='' ||
                    document.getElementById('buyDays').value &&  document.getElementById('buyNum').value===0){
                    document.getElementById('errBuyNum').innerText='限时课程必须输入节数'
                }else if(!(document.getElementById('buyDays').value &&  document.getElementById('buyNum').value)){
                    document.getElementById('errBuyType').innerText='限时课程必须同时输入节数和天数'
                }else{
                    document.getElementById('errBuyDays').innerText='';
                    document.getElementById('errBuyNum').innerText='';
                    document.getElementById('errBuyType').innerText='';
                }       
                document.getElementById('pay').value="";
                document.getElementById('realPay').value="";              
            }
            // if(buyTypeSelect.value==='常规课程'){      
            //     buyDaysInput.value='';              
            //     buyDaysInput.setAttribute('disabled','true');
            // }
            if(buyTypeSelect.value==='常规课程'){      
                if(buyClsName.value==='私教'){
                    buyNum.value='';
                    buyDaysInput.value='';              
                    buyDaysInput.setAttribute('disabled','true');
                    buyNum.disabled=false;
                    document.getElementById('pay').value="";
                    document.getElementById('realPay').value=""; 
                }else if(buyClsName.value==='9.9元私教'){
                    buyNum.value=1;
                    buyDaysInput.value=30;              
                    buyDaysInput.setAttribute('disabled','true');
                    buyNum.disabled='true';
                    document.getElementById('pay').value="9.9";
                    document.getElementById('realPay').value="9.9";   
                }else if(buyClsName.value==='活动赠课'){
                    buyNum.value="5";
                    buyDaysInput.value="";              
                    // buyDaysInput.setAttribute('disabled','false');
                    // buyNum.disabled='false';
                    buyDaysInput.disabled=false;
                    buyNum.disabled=false;
                    document.getElementById('pay').value="0";
                    document.getElementById('realPay').value="0";   
                }else{
                    buyNum.value='';
                    buyDaysInput.value='';              
                    buyDaysInput.setAttribute('disabled','true');
                    buyNum.disabled=false;
                    document.getElementById('pay').value="";
                    document.getElementById('realPay').value=""; 
                }                
            }

        }

        function generateBuyTypeSelect(data){
            let buyTypeSelect=document.getElementById('buyType')
            const buyTypes=data.cls_types;
            buyTypes.forEach((buyType,index)=>{
                let option=document.createElement('option');
                option.value=buyType;
                option.innerText=buyType;
                buyTypeSelect.appendChild(option);
                if(index===0){
                    option.selected=true;
                }
            });
            buyTypeSelect.addEventListener("change",function(){
                showBuyTypePrompt()
            });
        }

        function submitCheck(){
            const allInputBox=document.getElementById('inputContents');
            const inputElements=allInputBox.querySelectorAll('input');
            const selectElements=allInputBox.querySelectorAll('select');
            const dicIdEmp={
                'cusNameInput':'客户姓名',
                'buyCodeSelect':'购课编码',
                'buyNum':'购课节数',
                'buyDays':'购课天数',
                'pay':'应收金额',
                'realPay':'实收金额',
                'cashier':'收款人姓名',
                'incomeType':'收入类型'
            }
            try{
                    inputElements.forEach((input)=>{              
                        // console.log(input.value);
                        if(document.getElementById('buyType').value==='限时课程' || document.getElementById('buyType').value==='限时团课'){
                            if(input.id!=='comment' && input.id!=='admCmt' && !input.value){
                            throw new Error('输入项 '+dicIdEmp[input.id]+' 有空值或未选择');                        
                            }
                        }else{
                            if(input.id!=='comment' && input.id!=='admCmt' && input.id!=='buyDays' && !input.value){
                            throw new Error('输入项 '+dicIdEmp[input.id]+' 有空值或未选择'); 
                            }
                        }
                    
                    // const buyCodePattern=/^MH\d{5}.*\d{8}$/
                    // if(!buyCodePattern.test(document.getElementById('buyCode').value)){
                    //     throw new Error('购课编码有错误');
                    // }
                    
                    if(document.getElementById('buyDays').value==='0'|| document.getElementById('buyNum').value==='0'                        
                        ){
                        throw new Error('购买天数或节数不能有0值');
                    }      

                    

                    if(parseFloat(document.getElementById('pay').value)<0 || parseFloat(document.getElementById('realPay').value)<0){
                        throw new Error('购买金额不能小于0');
                    }

                    if(document.getElementById('buyType').value==='限时课程' || document.getElementById('buyType').value==='限时团课'){
                        if(
                            document.getElementById('buyDays').value==='' || document.getElementById('buyNum').value===''
                            || document.getElementById('buyDays').value===0 || document.getElementById('buyNum').value===0
                        ){
                            throw new Error('限时课程必须同时输入 购课节数 及 购课时长（天）');
                        }
                    }         
                    if(parseInt(document.getElementById('buyNum').value)<0){
                        throw new Error('购课节数必须为正数')
                    }          
                    if(parseInt(document.getElementById('buyDays').value)<0){
                        throw new Error('购课天数必须为正数')
                    }      
                    if(parseFloat(document.getElementById('pay').value)<0){
                        throw new Error('应收金额必须为正数')
                    }   
                    if(parseFloat(document.getElementById('realPay').value)<0){
                        throw new Error('实收金额必须为正数')
                    }   
                });

                selectElements.forEach((select)=>{
                    // console.log(select.value);
                    if(!select.value){
                        throw new Error('选择项 '+dicIdEmp[select.id]+' 未选择');
                    }
                });

                // if(document.getElementById('buyCodeSelect').value==='限时课程'){
                //         if(
                //             document.getElementById('buyDays').value==='' || document.getElementById('buyNum').value===''
                //             || document.getElementById('buyDays').value===0 || document.getElementById('buyNum').value===0
                //         ){
                //             throw new Error('限时课程必须同时输入 购课节数 及 购课时长（天）');
                //         }
                // } 
                return 'True';
            }catch(error){
                // alert('字段 '+error+' 有空格/未选择');
                return '输入项检测错误：'+error;
            }
        }

        function submit(){
            try{
                if(submitCheck()==='True'){
                    const operateTime=new Date();
                    // console.log(insId,insName,'line429')
                    const inputContents=document.getElementById('inputContents');
                    const inputElements=inputContents.querySelectorAll('input');
                    const dataKey=['客户编码及姓名','收款日期','购课节数','购课时长（天）','应收金额','实收金额','与应收一致','备注','管理员备注'];
                    n=0;
                    let data={};
                    // data加入输入的内容    
                    inputElements.forEach((input)=>{
                        // console.log(input.value);
                        data[dataKey[n]]=input.value;
                        n+=1;
                    });   
                    
                    // 添加consWithPay和admCmt到data
                    data['与应收一致'] = document.getElementById('consWithPay').checked ? 'yes' : 'no';
                    // data['adm_cmt'] = document.getElementById('admCmt').value;

                    //有效上课时段
                    data['有效上课时段'] =document.getElementById('validTime').value;

                    //如果使用优惠券
                    if(vcData){
                        // console.log('vcdata:',vcData);
                        const realPay=calRealPay();
                        if(realPay['realPayWithVcValue'] && realPay['realPayWithVcValue']>0){
                            data['实收金额']=realPay['realPayWithVcValue'];
                            data['管理员备注']=`使用优惠券${realPay['vcId']}，优惠${realPay['vcAmount']}元/折。`;
                            if(realPay['vcUseFor']==='deposit'){
                                data['管理员备注']=`已交过定金${realPay['vcAmount']}元。`;
                            }
                            let insIdPage;
                            if(insRole==='ins'){
                                insIdPage=insId;
                            }else{
                                insIdPage=insId;
                                //特殊，陆的情况
                                if(insRole==='admin'){
                                    if(insId==='LZADM002'){
                                        insIdPage='LZINS001';
                                    }
                                    
                                }
                            }
            
                            const today=new Date();
                            const vcUseData={
                                'vcId':document.getElementById('vcSel').value,
                                'cusId':document.getElementById('cusNameInput').value.trim(),
                                'buyFlowId':document.getElementById('buyCodeSelect').value,
                                'useDate':dateToString(today,'date'),
                                'oprId':insIdPage,
                                'oprDatetime':dateToString(today,'dateTime')
                            }

                            fetch('/write_vc_use',{
                                method:"POST",
                                headers:{
                                    'Content-Type':'application/json'
                                },
                                body:JSON.stringify(vcUseData)
                            })
                            .then(response=>response.json())
                            .then(data=>{
                                // console.log(data)
                                if(data.res==='ok'){
                                    console.log('vc use rec ok.')
                                }else{
                                    const errMsg=data.msg;
                                }
                                
                            })
                            .catch(error=>{
                                console.error('Error:',error.message)
                            });


                        }else{

                        }
                    }

                    
                                 



                    // data加入选择的内容           
                    // data['购课卡号']=document.getElementById('buyCodeSelect').value.split('-')[0];
                    data['购课流水号']=document.getElementById('buyCodeSelect').value;
                    data['购课卡号']=data['购课流水号'].split('-')[0];
                    data['购课类型']=document.getElementById('buyType').value;
                    data['购课名称']=document.getElementById('buyClsName').value;
                    data['收款人']=document.getElementById('cashier').value;
                    data['收入类别']=document.getElementById('incomeType').value;
                    data['operatorId']=insId;
                    data['operateTime']=dateToString(operateTime,'dateTime');

                    // 非限时课程，且购课名称为“私教”，时长设置为999天
                    if(['常规课程','常规团课'].includes(data['购课类型'])){
                        // data['购课时长（天）']=999;
                        if(document.getElementById('buyClsName').value==='私教'){
                            data['购课时长（天）']=999;
                        }else if(document.getElementById('buyClsName').value==='9.9元私教'){
                            data['购课时长（天）']=30;
                        }else if(document.getElementById('buyClsName').value==='活动赠课'){
                            data['购课时长（天）']=data['购课时长（天）'];
                        }else{
                            data['购课时长（天）']=999;
                        }
                    }

                    //改写页面的状态提示
                    document.getElementById('status').innerText='正在写入'
 
                    // console.log(data)

                    //写入薪酬结算表card_salary_stat
                    fetch('/write_cal_ins_salary',{
                        method:"POST",
                        headers:{
                            'Content-Type':'application/json'
                        },
                        body:JSON.stringify(data)
                    })
                    .then(response=>response.json())
                    .then(data=>{
                        // console.log(data)
                        if(data.res==='ok'){
                            console.log('新课记录薪酬标记未结算成功')
                            window.location.href='./index';
                        }else{
                            const errMsg=data.msg;
                            alert('新课记录薪酬标记未结算错误！！'+errMsg)
                        }
                        
                    })
                    .catch(error=>{
                        console.error('Error:',error.message)
                    });
                    

                    //写入购课表buy_rec_table
                    fetch('/write_buy',{
                        method:"POST",
                        headers:{
                            'Content-Type':'application/json'
                        },
                        body:JSON.stringify(data)
                    })
                    .then(response=>response.json())
                    .then(data=>{
                        // console.log(data)
                        if(data.res==='ok'){
                            alert('购课记录增加成功')
                            window.location.href='./index';
                        }else{
                            const errMsg=data.msg;
                            alert('购课未增加成功！！'+errMsg)
                        }
                        
                    })
                    .catch(error=>{
                        console.error('Error:',error.message)
                    });


                    
                    
                }else{
                    throw new Error(submitCheck());
                }            
            }catch(error){
                alert(error.message);
            }

        }

        function incomeTypeSelect(data){
            let incomeTypeSelect=document.getElementById('incomeType')
            const incomeTypes=data.income_types;
            incomeTypes.forEach(function(incomeType){
                let option=document.createElement('option');
                option.value=incomeType;
                option.innerText=incomeType;
                incomeTypeSelect.appendChild(option)
            })
        }

        function cashierSelect(data){
            let cashierSelect=document.getElementById('cashier')
            const cashiers=data.cashiers;
            cashiers.forEach(function(cashier){
                let option=document.createElement('option');
                option.value=cashier[0];
                option.innerText=cashier[1];
                cashierSelect.appendChild(option)
            })
        }

        function fillBuyCode(){
            // const buyCodeErrBox=document.getElementById('buyCodeErr');
            // buyCodeErrBox.innerText='';
            
            const cusName=document.getElementById('cusNameInput').value.trim();
            const dateInput=document.getElementById('dateInput').value.trim();
            const buyCode=document.getElementById('buyCode').value.trim();
            const dateTxt=dateInput.replace(/-/g,"")
            const ptn=/^LZ\d{3}.*\d{8}$/;
            if(buyCode===""){
                if (cusName !== "" && dateInput !== "" ) {
                    // var cusIDName=document.getElementById('cusNameInput').value
                    const testBuyCode=cusName+dateTxt
                    // console.log(testBuyCode)
                    if(ptn.test(testBuyCode)){
                        const buyCodeInput=document.getElementById('buyCode');
                        buyCodeInput.value=testBuyCode;
                    }else{
                        // input3.style.display = "none";
                    }
                    
                } else {
                    // input3.style.display = "none";
                }
            }
            //输入完毕后再检查购课编码中的日期是否正确
            isValidDate();
        }

        function generateClsNameSelect(data){     
            if(!data){
                data=tmplt_info
            }                
            const buyType=document.getElementById('buyType').value;
            if(buyType===''){
                buyType='限时课程';
            }

            // console.log('clsNameData:',data['cls_type_name_dic'][buyType])   
            const buyClsName=document.getElementById('buyClsName');
            buyClsName.innerHTML='';
            data['cls_type_name_dic'][buyType].forEach(clsName=>{
                const clsNameOpt=document.createElement('option');
                clsNameOpt.value=clsName;
                clsNameOpt.textContent=clsName;
                buyClsName.appendChild(clsNameOpt);
            });

            generateBuyCodeSelect();
        }

        function generateBuyCodeSelect(){
            showBuyTypePrompt();
            const currentTime=dateFormat(new Date(),'date_time_14_digits');
            // console.log(currentTime)
            const cusIdName=document.getElementById('cusNameInput').value;
            const buyType=document.getElementById('buyType').value;
            const buyClsName=document.getElementById('buyClsName').value;
            const buyDate=document.getElementById('dateInput').value.trim();
            // console.log('buyType:',buyType)
            fetch('./get_cus_cards_by_type', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                                },
                            body:JSON.stringify({'cus_id_name':cusIdName,'buy_type':buyType,'buy_cls_name':buyClsName,'buy_date':buyDate})
                            })
                            .then(response => response.json())
                            .then(data => {
                        //将data赋值给块变量cus_list，供后面的handleInput使用
                                // console.log(data);                               
                                if(data['res']==='ok'){
                                    const buyCodeSel=document.getElementById('buyCodeSelect');
                                    if(cusIdName){
                                        // console.log(data['card_ids'])
                                        
                                        buyCodeSel.innerText='';
                                        data['card_ids'].forEach(card=>{
                                            const opt=document.createElement('option');
                                            opt.value=card+'-'+currentTime;
                                            opt.text=card;
                                            buyCodeSel.appendChild(opt);

                                        });
                                    }else{
                                        buyCodeSel.innerText='';
                                    }
                                
                                }else{
                                    console.log('获取卡号错误')
                                }
                            })                 
                            .catch(error=>{
                                console.error('获取卡号错误',error)
                            });
        }

        function showVc(cusIdName){
            // const cusIdName=document.getElementById('cusNameInput').value.trim();
            const today=new Date();
            fetch('/get_cus_vc_list',{
                    method:"POST",
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body:JSON.stringify({'cusIdName':cusIdName,'today':dateToString(today,'date')})
            })
            .then(response=>response.json())
            .then(data=>{
                // console.log('vc card data:',data);
                const vcBox=document.getElementById('vcBox');
                if(data['res']==='ok'){   
                    vcData=data['data'];
                    let validCount=0;
                    vcData.forEach(item=>{
                        if(item['valid']==='yes'){
                            validCount+=1;
                        }
                    });

                    //当有效卡存在时
                    if(validCount>0){
                        vcBox.style.display='block';
                        const cardSelDiv=document.createElement('div');
                        cardSelDiv.classList.add('form-row');
                        const cardSel=document.getElementById('vcSel');      
                        cardSel.innerHTML='';
                        const opt=document.createElement('option');
                        opt.text='不使用卡券';
                        opt.value=0;
                        cardSel.appendChild(opt);
                        vcData.forEach(item=>{     
                            if(item['valid']==='yes'){
                                const opt=document.createElement('option');
                                let vcNameShow;
                                if(item['use_for']==='cel-birthday'){
                                    vcNameShow='生日卡'
                                }else if(item['use_for']==='deposit'){
                                    vcNameShow='定金'
                                }else{
                                    vcNameShow=item['vc_name']
                                }

                                opt.text=`${vcNameShow}-${item['vc_id']}`;
                                opt.value=item['vc_id'];   
                                cardSel.appendChild(opt);
                            }
                            
                        });

                        cardSel.addEventListener('change',()=>{calRealPay()});


                    }else{
                        vcBox.style.display='none';
                    }
                    
                }else{
                    vcBox.style.display='none';
                }
             
            })
            .catch(error=>console.log(error));
        }


        function calRealPay(){
            const vcId=document.getElementById('vcSel').value;
            // console.log('vcId:',vcId);
            const realPayWithVc=document.getElementById('realPayWithVc');
            realPayWithVc.innerHTML='';
            const realPayValue=document.getElementById('realPay').value.trim();
            let vcAmount;
            let realPayWithVcValue;
            let vcUseFor;
            for(i=0;i<vcData.length;i++){
                if(vcData[i]['vc_id']===vcId){
                    vcAmount=vcData[i]['amount']
                    vcUseFor=vcData[i]['use_for']
                    break;
                }
            }
            
            const submitBtn=document.getElementById('submitBtn');
            submitBtn.disabled=true;

            if(realPayValue && realPayValue!="0"){
                
                submitBtn.disabled=false;
                //代金券直接减
                if(vcAmount>0){
                    realPayWithVcValue=parseFloat(realPayValue)-parseFloat(vcAmount);
                    if(realPayWithVcValue>0){
                        realPayWithVc.innerHTML=`<span style="color:red;">使用代金券，减${vcAmount}元，实付${realPayWithVcValue}元。</span>`;
                        submitBtn.disabled=false;
                    }else{
                        realPayWithVc.innerHTML=`请输入大于${vcAmount}的金额`;
                        submitBtn.disabled=true;
                    }
                    
                }
                //折扣券打折
                if(vcAmount<0){
                    realPayWithVcValue=parseFloat(realPayValue)*parseFloat(vcAmount);
                    realPayWithVc.innerHTML=`使用折扣券，${(vcAmount*100).toFixed(0)}折，实付${realPayWithVcValue}元。`;
                    submitBtn.disabled=false;
                }
                
            }else{
                realPayWithVc.innerHTML='';
                realPayWithVcValue=0;
                submitBtn.disabled=false;
            }
            // console.log('rp:',realPayValue,'\nrp vc:',realPayWithVcValue,'\nvc:',vcAmount)
            return {'realPayWithVcValue':realPayWithVcValue,'vcAmount':vcAmount,'vcId':vcId,'vcUseFor':vcUseFor};      
        }


        async function handleInput() {
            hide_cus_buy();
            document.getElementById('buyCodeSelect').innerHTML='';
            document.getElementById('incomeType').disabled=false;

            //隐藏会员等级显示
            document.getElementById('stageBlock').style.display='none';

            // 获取输入框中的值
            const searchTerm = document.getElementById("cusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusNameResultList");
   
            if(searchTerm===''){
                const buyCodeSel=document.getElementById('buyCodeSelect');
                selectedName='';
                buyCodeSel.innerText='';
            }

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";
            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = name;                   
                    

                    // 添加点击事件监听器
                    listItem.addEventListener("click", async function() {

                        // 点击后将完整的姓名设置为输入框的值
                        selectedName=name;      
                        document.getElementById("cusNameInput").value=name;                  
                        // const buyCode=document.getElementById('buyCode');
                        // const buyCodeErr=document.getElementById('buyCodeErr');
                        // buyCode.value='';
                        // buyCodeErr.innerText='';
                        
                        //显示会员等级框
                        document.getElementById('stageBlock').style.display='block';
                        try{
                        const totalAmount = await getCusBuySum(name);
                            cusTotalAmount = totalAmount;
                            console.log('客户总购课金额：',totalAmount);
                            showCusStage(cusTotalAmount);

                        }catch(error){
                            console.error('获取客户购课总金额错误',error)
                            cusTotalAmout=0
                        }
                        
                        document.getElementById('buyType').disabled=false;
                        document.getElementById('buyNum').disabled=false;
                        document.getElementById('buyDays').disabled=false;
                        document.getElementById('pay').disabled=false;


                        // 检查课程类型，给出提示
                        showBuyTypePrompt();

                        // 填写进购课编号
                        // fillBuyCode();

                        //根据购课类型生成卡号，或选择旧卡号
                        generateBuyCodeSelect();
                        // 清空结果列表
                        resultList.innerHTML = "";  
                        resultList.style.display='none';


                        //点击姓名时读取购课记录
                        fetch('/get_cus_cls_infos', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                                },
                            body:JSON.stringify({'cus_name':selectedName})
                            })
                            .then(response => response.json())
                            .then(data => {
                        //将data赋值给块变量cus_list，供后面的handleInput使用
                            // console.log('buy list:',data);
                            buy_list=data['buy_list'];})
                            .catch(error=>{
                                console.error('读取购课记录错误：',error)
                            });

                        showVc(name);
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                }
            });
        
            resultList.classList.add("cus-list-result-blue");
            resultList.style.paddingLeft='20px';
        }


        function showCusStage(totalAmount){
            const ranges = Object.keys(cusStageConfig);
            let range = null;
            for (const rangeKey of ranges) {
            const [min, max] = rangeKey.split('-').map(Number);
            if (Math.round(totalAmount/10) >= Math.round(min/10) && Math.round(totalAmount/10) < Math.round(max/10)) {
                range = cusStageConfig[rangeKey];
                console.log('所在的range：',range);
                break;
            }
            }

            // 根据会员等级显示相应的勋章
            let badgeClass = '';
            let badgeText = range.name;
            
            switch(range.name) {
                case '心动行动':
                    badgeClass = 'badge badge-bronze';                    
                    break;
                case '渐入佳境':
                    badgeClass = 'badge badge-silver';
                    break;
                case '身体力行':
                    badgeClass = 'badge badge-gold';
                    break;
                case '知行合一':
                    badgeClass = 'badge badge-platinum badge-glow';
                    break;
                default:
                    badgeClass = 'badge badge-bronze';
            }

            document.getElementById(`stage`).innerHTML=`<span style='font-size:10px;font-weight:bold;'>${range.star} @ ${Math.round(totalAmount/10)}分</span>`;
            document.getElementById(`stage`).style.fontSize='14px';
            if(range.star && ['二星会员','三星会员','四星会员'].includes(range.star)){
                document.getElementById(`stage`).innerHTML=`<div style="line-height:1.2;margin:0;padding:0;text-align:center;"><div style='font-size:10px;font-weight:bold;'>${range.star} @ ${Math.round(totalAmount/10)}分</div><div style="font-size:10px;margin:0;padding:2px;color:#ff6b35;font-weight:bold;">购课即享优惠</div></div>`;
            }
            document.getElementById(`badge`).innerHTML=`<div class="${badgeClass}" style='margin-top:8px;'>${badgeText}勋章</div>`;
            document.getElementById('offsetAmount').innerHTML=`<div style='font-size:10px;'>每次购课立减${range.offset_amount}元</div>`;

           
        }


        function getCusBuySum(name){
        return fetch(`/get_cus_buy_sum?cus_id=${encodeURIComponent(name.slice(0,7))}`)
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){
                    console.log('get cus buy sum data:',data);
                    return parseFloat(data.data[0]['total_amount']);
                } else {
                    throw new Error(data.msg || '获取会员总购课金额失败');
                }                     
            })
            .catch(error=>{
                console.log('获取会员总购课金额错误：',error);
                throw error;
            });  
        }      
    
        function get_cus_info() {
            var selectedName = document.getElementById("cusNameInput").value;
            clear_other_div()
            fetch('/get_cus_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ selected_name: selectedName })
            })
            .then(response => response.json())
            .then(data => {                
                // console.log(data)
                show_cus_info(data)
                document.getElementById("cus_name").innerText = data['会员编码及姓名'];
                document.getElementById("total_cls_days").innerText = data['上课总天数'];
                document.getElementById("total_pay").innerText = data['总消费金额'];
                document.getElementById("normal_remain").innerText = data['剩余节数-常规课程']
                document.getElementById("lmt_yn").innerText = data['限时课程是否有效']
                document.getElementById("lmt_due_date").innerText = data['限时课程到期日']

                format_date();
            })
            .catch(error => {
                console.error('Error:', error) 
                document.getElementById("show_info").style.display='none';
                document.getElementById("open_cus_fn_res").innerText='';
                document.getElementById("err_no_result").innerText='无结果';
            
                });
            

        }

        function format_date(){
            var dateContent = document.getElementById("lmt_due_date").innerText;
            if (dateContent!='-'){
                var dateObject = new Date(dateContent);
                // 将日期按照你想要的格式进行处理
                var year = dateObject.getFullYear();
                var month = ("0" + (dateObject.getMonth() + 1)).slice(-2);
                var day = ("0" + dateObject.getDate()).slice(-2);

                // 拼接日期字符串，例如：YYYY-MM-DD
                var formattedDate = year + "-" + month + "-" + day;

                // 将日期显示在页面上
                document.getElementById("lmt_due_date").innerText = formattedDate;
            }
            
        }
  
  
        function isValidDate(){
            const buyCodeErrBox=document.getElementById('buyCodeErr');
            buyCodeErrBox.innerText='';
            const buyCode=document.getElementById('buyCode').value;
            const dateStr=buyCode.substring(buyCode.length-8);
            const ptn=/^\d{8}/;
            // console.log(buyCode)
            console.log(moment(dateStr,"YYYYMMDD").isValid() && ptn.test(dateStr))
            if(moment(dateStr,"YYYYMMDD").isValid() && ptn.test(dateStr)){    
                buyCodeErrBox.innerText='';
            }else{
                buyCodeErrBox.innerText='日期错误';
                allError.dateError=1;
            }
            console.log(allError);
        }

    </script>
</body>
</html>
